package com.hzit.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hzit.mapper.ClassesMapper;
import com.hzit.mapper.StudentMapper;
import com.hzit.pojo.*;
import com.hzit.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Service
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentMapper studentMapper;
	@Autowired
	private ClassesMapper classesMapper;
	//1. 查询所有学生
	@Override
	public List<Student> findAll() {
		List<Student> students = studentMapper.selectByExample(null);
		for (Student student : students) {
			Classes classes = classesMapper.selectByPrimaryKey(student.getCid());
			student.setCname(classes.getCname());
		}
		return students;
	}

	//2. 条件查询带分页
	@Override
	public PageResult<Student> search(int page, int pageSize, StudentVo vo) {
		//2.1 开始分页
		PageHelper.startPage(page,pageSize);
		//2.2 定义查询条件对象
		StudentExample example = new StudentExample();
		StudentExample.Criteria criteria = example.createCriteria();
		//2.3 根据查询参数为查询条件对象赋值
		if(StrUtil.isNotBlank(vo.getSname())){
			criteria.andSnameLike("%" + vo.getSname() + "%");
		}
		if(StrUtil.isNotBlank(vo.getAddr())){
			criteria.andAddrLike("%" + vo.getAddr() + "%");
		}
		if(vo.getCid() != null && vo.getCid() != 0){
			criteria.andCidEqualTo(vo.getCid());
		}
		List<Student> students = studentMapper.selectByExample(example);
		for (Student student : students) {
			Classes classes = classesMapper.selectByPrimaryKey(student.getCid());
			student.setCname(classes.getCname());
		}
		//2.4 将students转换Page<Student>对象
		Page<Student> studentPage = (Page<Student>) students;
		//2.5 返回
		return new PageResult<>(studentPage.getTotal(),studentPage.getResult());
	}

	//3. 添加学生
	@Override
	public void insert(Student student) {
		studentMapper.insert(student);
	}
	//4. 修改学生
	@Override
	public void update(Student student) {
		studentMapper.updateByPrimaryKey(student);
	}

	//5. 删除学生
	@Override
	public void delete(String sid) {
		studentMapper.deleteByPrimaryKey(new Integer(sid));
	}
}
